package cn.itcast.music.ui.home;

import static android.content.Context.BIND_AUTO_CREATE;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import cn.itcast.music.R;
import cn.itcast.music.databinding.FragmentHomeBinding;
import cn.itcast.music.entity.Music;
import cn.itcast.music.service.EmptyServiceConnection;
import cn.itcast.music.service.MusicPlayingService;
import cn.itcast.music.ui.listen.ListenActivity;
import cn.itcast.music.util.MusicUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HomeFragment extends Fragment {

    private static final String LOG_TAG = "App-HomeFragment";

    private FragmentHomeBinding binding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);

        // HomeFragment 总是先于 MainActivity 加载，因此，
        // 在 HomeFragment 中申请权限和初始化 MusicUtil 中的音乐数据
        // 读取本地音乐需要申请权限
        doWithNecessaryPermission(() -> {
            // 初始化音乐数据
            MusicUtil.initMusicData(requireContext());

            List<Music> musicList = MusicUtil.getReadonlyMusicList();
            initViewsWithData(musicList);
            setListener(musicList);

            // 绑定（启动）音乐播放服务到 MainActivity，让其保持运行，直到应用被关闭
            bindMusicPlayingService();
        });

        return binding.getRoot();
    }

    private void doWithNecessaryPermission(Runnable runAfterGranted) {
        // 配置权限列表
        List<String> permissions = new ArrayList<>();
        if (VERSION.SDK_INT >= VERSION_CODES.S_V2) {
            permissions.add("android.permission.READ_MEDIA_AUDIO");
        } else {
            permissions.add("android.permission.READ_EXTERNAL_STORAGE");
        }
        if (VERSION.SDK_INT >= VERSION_CODES.TIRAMISU) {
            permissions.add("android.permission.POST_NOTIFICATIONS");
        }

        // 检测是否都通过
        if (isAllGranted(permissions)) {
            runAfterGranted.run();
        } else {
            registerForActivityResult(new RequestMultiplePermissions(),
                    grantedMap -> {
                        if (isAllGranted(grantedMap)) {
                            Log.d(LOG_TAG, "权限申请成功");
                            Toast.makeText(requireContext(), "权限申请成功",
                                    Toast.LENGTH_SHORT).show();
                            runAfterGranted.run();
                        } else {
                            Log.d(LOG_TAG, "必要权限申请失败");
                            Toast.makeText(requireContext(), "必要权限申请失败",
                                    Toast.LENGTH_SHORT).show();
                            requireActivity().finish();
                        }
                    }).launch(permissions.toArray(new String[0]));
        }
    }

    private boolean isAllGranted(List<String> permissions) {
        for (String permission : permissions) {
            if (requireContext().checkSelfPermission(permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private boolean isAllGranted(Map<String, Boolean> isGranted) {
        for (Entry<String, Boolean> entry : isGranted.entrySet()) {
            if (Boolean.FALSE.equals(entry.getValue())) {
                return false;
            }
        }
        return true;
    }

    private void bindMusicPlayingService() {
        Intent intent = new Intent(requireContext(), MusicPlayingService.class);
        requireContext().bindService(intent, new EmptyServiceConnection(),
                BIND_AUTO_CREATE);
    }

    @SuppressLint("SetTextI18n")
    private void initViewsWithData(List<Music> musicList) {
        binding.rvMusicList.setAdapter(new MusicListAdapter(musicList));
        binding.rvMusicList.setLayoutManager(
                new LinearLayoutManager(requireContext()));
        binding.tvTotal.setText("播放全部（ " + musicList.size() + " 首）");
    }

    private void setListener(List<Music> musicList) {
        OnClickListener listener = view -> {
            if (view.getId() == R.id.tv_total) {
                Log.d(LOG_TAG, "用户播放全部音乐！" + musicList);
                Intent intent = new Intent(requireContext(),
                        ListenActivity.class);
                intent.putExtra("position", 0);
                requireContext().startActivity(intent);
            }
        };
        binding.tvTotal.setOnClickListener(listener);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}
